/**
 * @(#)CacheParamManager.java 2017年4月15日
 * Copyright(C) 2017 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.domian.MonitorConfigBean;
import org.jsbd.boss.service.IMonitorConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * 缓存定义字段值管理
 * 
 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
 * @version 1.0.0
 */
@Service
public class CacheParamManager {
	public static final Logger LOGGER = LoggerFactory.getLogger(CacheParamManager.class);

	private static Map<String, Object> paramsMap = new ConcurrentHashMap<>();

	@Resource
	private RedisClient redisClient;
	@Resource
	private IMonitorConfigService monitorConfigService;

	/**
	 * 
	 * getParamValue:缓存缓存设置的值
	 * 
	 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
	 * @param key
	 * @return
	 */
	public Object getParamValue(String key) {
		Object value = paramsMap.get(key);
		try {
			if (value == null) {
				value = redisClient.get(key);
				if (value != null) {
					paramsMap.put(key, value);
				}
			}
		} catch (Exception e) {
			LOGGER.error("CacheParamManager getValue error", e);
		}
		return value;
	}

//	@PostConstruct
	private void init() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				int sleepTime = 20 * 1000;
				while (true) {
					try {
						if (paramsMap != null) {
							String[] keys = (String[]) paramsMap.keySet().toArray(new String[0]);
							for (String key : keys) {
								Object value = redisClient.get(key);
								LOGGER.info("cache key:{} value:{}", key, value);
								if (value != null && StringUtils.isNotBlank(value.toString())) {
									paramsMap.put(key, value);
								} else {
									paramsMap.remove(key);
								}
							}
						}
						List<MonitorConfigBean> keyList = monitorConfigService.getMonitorConfigList(null);
						for (MonitorConfigBean bean : keyList) {
							String key = bean.getItemKey();
							String value = bean.getItemValue();
							redisClient.put(key, value);
							paramsMap.put(key, value);
						}
						Thread.sleep(sleepTime);
					} catch (Exception e) {
						LOGGER.error("CacheParamManager error ", e);
					}
				}
			}
		}).start();
	}

}
